#include "dbtrack.h"
#include "connection.h"
#include <QSqlQuery>
#include <QString>
#include <QSqlError>
#include <QVariant>
#include <QSqlRecord>

DbTrack::DbTrack()
{
}

bool DbTrack::create(QList<DtTrack *> &track)
{
    if(track.isEmpty())
        return true;
    /* create and setup a progress bar. */
    Connection *con = Connection::getInstance();
//    WProgressBar * progress = WProgressBar::getInstance();
//    progress->setMaximumStep(track.size());
//    progress->setText("Inserting track");
    /* 999 is the maximum variable in query */
    const int MaxBoucle = 999 / 11;
    if(con->isConnected())
    {
        QSqlQuery query;
        int i = 0;
        int nbInsert = 0;
        QList<DtTrack *>::ConstIterator itG = track.constBegin();
        QList<DtTrack *>::ConstIterator itL = track.constBegin();

        while(itG != track.constEnd())
        {
            QString cmd = "INSERT INTO Track (name, time, lyrics, score, num,"
                    " recovery, heart, location, album, Artist, genre)";
            i = 0;
            for(;itG != track.constEnd() && i < MaxBoucle; itG ++)
            {
//                progress->progress();
                if((*itG)->getId() == -1)
                {
                    if(i == 0)
                        cmd += " SELECT";
                    else
                        cmd += " UNION ALL SELECT";
                    QString n;
                    n.setNum(i);
                    cmd += " :n" + n + " , :t" + n + ", :l" + n + ", :s" + n
                            + ", :nu" + n + ", :r" + n + ", :h" + n + ", :lo" + n
                            + ", :al" + n + ", :ar" + n + ", :g" + n ;
                    i ++;
                }
            }
            if(i == 0)
                return true;
            nbInsert += i;
            if(!query.prepare(cmd))
            {
                qDebug() << query.lastQuery() << query.lastError().text();
                return false;
            }

            i = 0;
            for(; itL != track.constEnd() && i < MaxBoucle; itL ++)
            {
//                progress->progress();
                if((*itL)->getId() == -1)
                {
                    QString n;
                    n.setNum(i);
                    query.bindValue(":n" + n, (*itL)->getName());
                    query.bindValue(":t" + n, (*itL)->getTime().toString("hh:mm:ss"));
                    query.bindValue(":l" + n, (*itL)->getLyrics());
                    query.bindValue(":s" + n, (*itL)->getScore());
                    query.bindValue(":nu" + n, (*itL)->getNumber());
                    query.bindValue(":r" + n, (*itL)->getRecovery() == NULL ?
                                        -1 : (*itL)->getRecovery()->getId());
                    query.bindValue(":h" + n, (*itL)->getHeart() ? "1" : "0");
                    query.bindValue(":lo" + n, (*itL)->getLocation());
                    query.bindValue(":al" + n, (*itL)->getAlbums().size() == 0 ?
                                        -1
                                      : (*itL)->getAlbums().front()->getId());
                    query.bindValue(":ar" + n, (*itL)->getArtists().size() == 0
                                    ? -1
                                    : (*itL)->getArtists().front()->getId());
                    query.bindValue(":g" + n, (*itL)->getGenres().size() == 0 ?
                                        -1
                                      : (*itL)->getGenres().front()->getId());
                    i ++;
                }
            }
            if(!query.exec())
            {
                qWarning() << query.lastQuery() << query.lastError().text();
            }
            query.finish();
        }
        QSqlQuery q("select max(id) as id from track");
        if(q.next())
        {
            int lastId = q.value(0).toInt();
            int beforeId = lastId + 1 - nbInsert;
            for(QList<DtTrack *>::Iterator itId = track.begin();
                itId != track.end(); itId ++)
            {
                if((*itId)->getId() == -1)
                {
                    (*itId)->setId(beforeId);
                    beforeId++;
                }
            }
        }
//        progress->stop();
        return true;
    }
    return false;
}

bool DbTrack::destroy(const QList<DtTrack *> & track)
{
    if(track.isEmpty())
        return true;

    Connection *con = Connection::getInstance();
    if(con->isConnected())
    {
        QString requete = "DELETE FROM Track WHERE id = ?";
        for(int i = 1; i < track.size(); i++)
        {
            requete += " or id = ?";
        }
        QSqlQuery query;
        query.prepare(requete);
        int i = 0;
        for(QList<DtTrack *>::ConstIterator it = track.constBegin();
            it != track.constEnd(); it++)
        {
            query.bindValue(i, (*it)->getId());
            i++;
        }
        if(!query.exec())
        {
            qWarning() << dbTrackStr << dbTrackDestroy
                     << query.lastError().text();
            return false;
        }
        return true;
    }
    return false;
}

bool DbTrack::update(const QList<DtTrack *> &track)
{
    if(track.isEmpty() <= 0)
        return true;

//    Connection *con = Connection::getInstance();
//    if(con->isConnected())
//    {
//        QSqlQuery query;
//        query.prepare("UPDATE FROM track WHERE id = :id set name = :name,"
//                      " time = :time, lyrics = :lyrics, score = :score,"
//                      " num = :num, recovery = :recovery, heart = :heart");
//        query.bindValue(":id", track.getId());
//        query.bindValue(":name", track.getName());
//        query.bindValue(":time", track.getTime().toString("hh:mm:ss"));
//        query.bindValue(":lyrics", track.getLyrics());
//        query.bindValue(":score", track.getScore());
//        query.bindValue(":num", track.getNumber());
//        query.bindValue(":recovery", track.getRecovery()->getId());
//        query.bindValue(":heart", track.getHeart());
//        if(!query.exec())
//        {
//            Journal::print(Journal::Err, dbTrackStr, dbTrackUpdate,
//                           query.lastError().text());
//            return false;
//        }
//        return true;
//    }
//    return false;
    return true;
}

bool DbTrack::setHeart(const DtTrack &track)
{
    Connection *con = Connection::getInstance();
    if(con->isConnected())
    {
        QString requete = "UPDATE track SET heart = :heart WHERE id = :id";
        QSqlQuery query;
        query.prepare(requete);
        query.bindValue(":heart", track.getHeart() ? 1 : 0);
        query.bindValue(":id", track.getId());
        if(!query.exec())
        {
            qWarning() << dbTrackStr << query.lastQuery()
                       << query.lastError().text();
            return false;
        }
        return true;
    }
    return false;
}
